package factoryProtocol;


public class Parser {
    private static final int IDLE = 1;
    private static final int STX1 = 2;       // 环境设备固定是1字节，固定0xFE
    private static final int STX2 = 3;       // 环境设备固定是1字节，固定0xDC
    private static final int VERSION1 = 4;   // 环境设备固定是1字节
    private static final int IMEI = 5;       // 环境设备固定是6字节, 物联网卡的卡号
    private static final int SESSION = 6;    // 环境设备固定是4字节, 累加的数字
    private static final int ORDER = 7;      // 环境设备固定是1字节 {0x03}
    private static final int LEN = 8;  //    // 环境设备固定2字节
    private static final int DATA = 9;      // 环境设备固定是24字节
    private static final int FCS = 10;       // 环境设备固定是1字节 {0x00}

    private static boolean msg_received;

    private Packet packet = new Packet();

    private int states = IDLE;
    private int lenTemp = 0;  // 下一个字段字节数

    public Packet message_parse_char(byte b) {
        msg_received = false;
        //System.out.println("状态："+states);
        switch (states + 1) {
            case STX1:
                if (b == Packet.STX1) {
                    states = STX1;
                }else{
                    states = IDLE;
                }
                break;
            case STX2:
                if (b == Packet.STX2) {
                    states = STX2;
                }else{
                    states = IDLE;
                }
                break;
            case VERSION1:
                packet.session = b;
                states = VERSION1;
                lenTemp = 6;
                break;
            case IMEI:
                packet.imei[6-lenTemp] = b;
                lenTemp--;
                if(lenTemp==0){
                    states = IMEI;
                    lenTemp = 4;
                    packet.session = 0;
                }
                break;
            case SESSION:
                packet.session = packet.session<<8 | b;
                lenTemp--;
                if(lenTemp==0){
                    states = SESSION;
                }
                break;
            case ORDER:
                packet.order = b;
                states = ORDER;
                lenTemp = 2;
                packet.len = 0;
                break;
            case LEN:
                packet.len = packet.len<<8 | b;
                lenTemp--;
                if(lenTemp==0){
                    states = LEN;
                    packet.setPayloadLen(packet.len);
                    packet.cleanPayload();
                }
                break;
            case DATA:
                packet.payload.add(b);
                if (packet.payload.size()>=packet.len) {
                    states = DATA;
                }
                break;
            case FCS:
                if (b == packet.FCS) {
                    msg_received = true;
                }
                states = IDLE;
                break;
        }
        return msg_received ? packet : null;
    }
}